<template>
  <div class="login">
    <a-form
      :form="form"
      class="user-layout-login"
      ref="formLogin"
      id="formLogin"
    >
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" tab="账号密码登陆">
          <!--用户名-->
          <a-form-item>
            <a-input
              size="large"
              v-decorator="[
                'account',
                validatorRules.account,
                { validator: this.handleAccount }
              ]"
              type="text"
              placeholder="请输入账户名/邮箱/手机号"
            >
              <a-icon
                slot="prefix"
                type="user"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>
          <!--密码-->
          <a-form-item>
            <a-input
              v-decorator="['password', validatorRules.password]"
              size="large"
              type="password"
              autocomplete="false"
              placeholder="请输入密码"
            >
              <a-icon
                slot="prefix"
                type="lock"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>
          <!--验证码-->
          <a-row :gutter="0" v-if="this.showCode === true">
            <a-col :span="14">
              <a-form-item>
                <a-input
                  v-decorator="['inputCode', validatorRules.inputCode]"
                  size="large"
                  type="text"
                  @change="inputCodeChange"
                  placeholder="请输入图形验证码"
                >
                  <a-icon
                    slot="prefix"
                    v-if="inputCodeContent === verifiedCode"
                    type="smile"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                  />
                  <a-icon
                    slot="prefix"
                    v-else
                    type="frown"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                  />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <j-graphic-code @success="generateCode" style="float: right" />
            </a-col>
          </a-row>
        </a-tab-pane>

        <a-tab-pane key="tab2" tab="短信验证码登陆">
          <a-form-item>
            <a-input
              v-decorator="['mobile', validatorRules.mobile]"
              size="large"
              type="text"
              placeholder="手机号"
            >
              <a-icon
                slot="prefix"
                type="mobile"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input
                  v-decorator="['captcha', validatorRules.captcha]"
                  size="large"
                  type="text"
                  placeholder="短信验证码"
                >
                  <a-icon
                    slot="prefix"
                    type="mail"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                  />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="sendSmsCaptcha"
                v-text="
                  (!state.smsSendBtn && '获取验证码') ||
                    state.time + 's可重新获取'
                "
              >
              </a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>

      <!--自动登录-->
      <a-form-item>
        <a-checkbox v-model="formLogin.rememberMe">自动登陆</a-checkbox>
        <!--
        <router-link :to="{ name: 'alteration'}" class="forge-password" style="float: right;">
          忘记密码
        </router-link>
        <router-link :to="{ name: 'register'}" class="forge-password" style="float: right;margin-right: 10px" >
          注册账户
        </router-link>
        -->
      </a-form-item>

      <!--登录-->
      <a-form-item style="margin-top:24px">
        <a-button
          style="width: 100%; margin-top: 4px"
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loading"
          @click.stop.prevent="handleSubmit"
          :disabled="loading"
          >确定
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import JGraphicCode from "../../components/tool/JGraphicCode";
import { encrypt } from "../../utils/crypto";

const emailRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
const mobileRegex = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
export default {
  name: "Login",
  components: {
    JGraphicCode
  },
  data() {
    return {
      form: this.$form.createForm(this),
      customActiveKey: "tab1",
      // 登陆类型: 0 用户名, 1 邮箱, 2 手机号
      loginType: 0,
      loading: false,
      error: "",
      activeKey: "1",
      state: {
        time: 60,
        smsSendBtn: false
      },
      formLogin: {
        account: "",
        password: "",
        captcha: "",
        mobile: "",
        rememberMe: true
      },
      showCode: false,
      validatorRules: {
        account: {
          rules: [
            {
              required: true,
              message: "请输入用户名/邮箱/手机号",
              validator: "click"
            }
          ]
        },
        password: {
          rules: [
            { required: true, message: "请输入密码!", validator: "click" }
          ]
        },
        mobile: {
          rules: [
            { required: true, message: "请输入正确的手机号!" },
            { validator: this.validateMobile }
          ]
        },
        captcha: { rules: [{ required: true, message: "请输入短信验证码!" }] },
        inputCode: {
          rules: [
            { required: true, message: "请输入图形验证码!" },
            { validator: this.validateInputCode }
          ]
        }
      },
      verifiedCode: "",
      inputCodeContent: "",
      inputCodeNull: true
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
    copyright() {
      return this.$store.state.setting.copyright;
    }
  },
  created() {
    this.$db.clear();
    this.$router.options.routes = [];
    this.showVerifiedCode();
  },
  methods: {
    handleAccount(rule, value, callback) {
      if (emailRegex.test(value)) {
        this.loginType = 1;
      } else if (mobileRegex.test(value)) {
        this.loginType = 2;
      } else {
        this.loginType = 0;
      }
      callback();
    },
    handleTabClick(key) {
      this.customActiveKey = key;
      // this.form.resetFields()
    },
    showVerifiedCode() {
      this.$get(`/api/login/showVerifiedCode`)
        .then(r => {
          console.log(r);
          this.showCode = r.data.data;
        })
        .catch(() => {
          this.showCode = false;
        });
    },
    generateCode(value) {
      this.verifiedCode = value.toLowerCase();
    },
    inputCodeChange(e) {
      this.inputCodeContent = e.target.value;
      if (!e.target.value || e.target.value === 0) {
        this.inputCodeNull = true;
      } else {
        this.inputCodeContent = this.inputCodeContent.toLowerCase();
        this.inputCodeNull = false;
      }
    },
    handleSubmit() {
      let that = this;
      that.loading = true;
      if (that.customActiveKey === "tab1") {
        // 使用账号密码登陆
        that.form.validateFields(
          ["account", "password", "inputCode"],
          { force: true },
          (err, values) => {
            if (!err) {
              if (emailRegex.test(values.account)) {
                that.loginType = 1;
              } else if (mobileRegex.test(values.account)) {
                that.loginType = 2;
              } else {
                that.loginType = 0;
              }

              this.$post("api/login", {
                account: values.account,
                password: encrypt(values.password),
                rememberMe: that.formLogin.rememberMe,
                loginType: that.loginType
              })
                .then(r => {
                  console.log(r);
                  let success = r.data.success;
                  if (success) {
                    this.saveLoginData(r.data.data);
                    setTimeout(() => {
                      this.loading = false;
                      this.showWelcome();
                    }, 500);
                    this.$router.push("/");
                  } else {
                    this.errorMsg(r.data.message, "登录异常");
                    this.loading = false;
                  }
                })
                .catch(() => {
                  setTimeout(() => {
                    this.loading = false;
                  }, 500);
                });
            } else {
              that.loading = false;
            }
          }
        );
      } else {
        // 使用短信验证码登陆
        that.form.validateFields(
          ["mobile", "captcha"],
          { force: true },
          (err, values) => {
            if (!err) {
              this.$post("api/login/sms", {
                mobile: values.mobile,
                captcha: values.captcha,
                rememberMe: that.formLogin.rememberMe
              })
                .then(r => {
                  let success = r.data.success;
                  if (success) {
                    let data = r.data.data;
                    this.saveLoginData(data);
                    setTimeout(() => {
                      this.loading = false;
                      this.showWelcome();
                    }, 500);
                    this.$router.push("/");
                  } else {
                    this.errorMsg(r.data.message, "登录异常");
                  }
                })
                .catch(() => {
                  setTimeout(() => {
                    this.loading = false;
                  }, 500);
                });
            } else {
              that.loading = false;
            }
          }
        );
      }
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(mobileRegex).test(value)) {
        callback();
      } else {
        callback("您的手机号码格式不正确!");
      }
    },
    /* 发送短信验证码 */
    sendSmsCaptcha(e) {
      e.preventDefault();
      let that = this;
      this.form.validateFields(["mobile"], { force: true }, (err, values) => {
        if (!values.mobile) {
          that.smsFailed("请输入手机号");
        } else if (!err) {
          this.state.smsSendBtn = true;
          let interval = window.setInterval(() => {
            if (that.state.time-- <= 0) {
              that.state.time = 60;
              that.state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          let smsParams = {};
          smsParams.mobile = values.mobile;
          smsParams.smsMode = "0";
          console.log("begin to call /api/sms ");
          this.$post("/api/sms", smsParams)
            .then(res => {
              console.log(res);
              if (!res.data.success) {
                this.smsFailed(res.data.message);
              }
            })
            .catch(err => {
              clearInterval(interval);
              that.state.time = 60;
              that.state.smsSendBtn = false;
              this.requestFailed(err.data.message);
            });
        }
      });
    },
    validateInputCode(rule, value, callback) {
      if (!value || this.verifiedCode === this.inputCodeContent) {
        callback();
      } else {
        callback("您输入的验证码不正确，请重新输入!");
      }
    },
    errorMsg(msg, desc) {
      this.$notification["error"]({
        message: msg,
        description: desc,
        duration: 4
      });
    },
    smsFailed(err) {
      this.$notification["error"]({
        message: err,
        description: "短信异常",
        duration: 4
      });
    },
    requestFailed(err) {
      this.$notification["error"]({
        message: err,
        description: "请求异常",
        duration: 4
      });
      this.loading = false;
    },
    ...mapMutations({
      setToken: "account/setToken",
      setExpireTime: "account/setExpireTime",
      setPermissions: "account/setPermissions",
      setRoles: "account/setRoles",
      setUser: "account/setUser",
      setTheme: "setting/setTheme",
      setLayout: "setting/setLayout",
      setMultipage: "setting/setMultipage",
      fixSiderbar: "setting/fixSiderbar",
      fixHeader: "setting/fixHeader",
      setColor: "setting/setColor"
    }),
    saveLoginData(data) {
      this.setToken(data.token);
      this.setExpireTime(data.expireTime);
      this.setUser(data.user);
      this.setPermissions(data.permissions);
      this.setRoles(data.roles);
      this.setTheme(data.config.theme);
      this.setLayout(data.config.layout);
      this.setMultipage(data.config.multiPage === "1");
      this.fixSiderbar(data.config.fixSiderbar === "1");
      this.fixHeader(data.config.fixHeader === "1");
      this.setColor(data.config.color);
    },
    showWelcome() {
      const date = new Date();
      const hour = date.getHours();
      let time =
        hour < 6
          ? "早上好"
          : hour <= 11
          ? "上午好"
          : hour <= 13
          ? "中午好"
          : hour <= 18
          ? "下午好"
          : "晚上好";
      this.$notification.success({
        message: "欢迎",
        description: `${time}，欢迎回来`
      });
    }
  }
};
</script>

<style lang="less" scoped>
.login {
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .icon {
    font-size: 24px;
    color: rgba(0, 0, 0, 0.2);
    margin-left: 16px;
    vertical-align: middle;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: #1890ff;
    }
  }
}
</style>
